package com.leige.webconfig.Exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 异常处理类-处理所有未捕获的异常
 * 
 */

@Component
public class CustomExceptionHandler implements HandlerExceptionResolver {

	private final static Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
	private final static ModelAndView defaultModel = new ModelAndView();
	@Override
	public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object object, final Exception exception) {
		
		try {
			response.setContentType("application/json;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			if (exception instanceof CustomException){
				CustomException exp=(CustomException) exception;
				response.sendError(exp.getCode(),  exception.getMessage());
				if (logger.isDebugEnabled()) {
					logger.debug("捕获到异常",exp);
				}
			}else{
				response.sendError(500, "未捕获的程序异常,"+exception.getMessage());
				if (logger.isInfoEnabled()) {
					logger.info("已捕获到程序异常", exception);
				}
			}
			response.flushBuffer();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return defaultModel;
	}
}
